package tech.yixiyun.framework.kuafu.component.unregister;


import tech.yixiyun.framework.kuafu.controller.PathResolver;
import tech.yixiyun.framework.kuafu.controller.annotation.Controller;
import tech.yixiyun.framework.kuafu.controller.annotation.Route;
import tech.yixiyun.framework.kuafu.controller.route.RouteContext;
import tech.yixiyun.framework.kuafu.view.View;
import tech.yixiyun.framework.kuafu.log.LOGGER;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Controller类解析器，注意类的可见范围只能在此包内，不能被外部调用，因为这里的逻辑是必须先注册Bean，生成代理类后
 * 才能在解析Controller
 */
public class ControllerComponentUnregistrar implements IComponentUnregistrar {

    @Override
    public boolean unregister(Class clazz) {

        Controller controller = (Controller) clazz.getAnnotation(Controller.class);
        if (controller != null) {

            String basePath = PathResolver.resolve(clazz.getSimpleName(), controller.value());


            unregisterRoute(basePath, clazz);

        }

        return true;
    }

    /**
     * 扫描方法，生成路由
     * @param basePath
     * @param clazz
     */
    private void unregisterRoute(String basePath, Class clazz) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) == false && View.class.isAssignableFrom(method.getReturnType())) {
                String fullPath = basePath ;
                Route route = method.getAnnotation(Route.class);
                if (route != null) {
                    fullPath = route.value();
                } else {
                    fullPath += "/" + method.getName();
                }
                if (fullPath.startsWith("/") == false) {
                    fullPath = "/" + fullPath;
                }
                LOGGER.trace("Route注册：" + fullPath + "  " + method.getDeclaringClass().getName()+":"+method.getName()+"()");

                RouteContext.unregister(fullPath);

            }
        }

    }

}
